package com.bieber.smartpost.util;

import com.jbeer.framework.JBeer;

import java.io.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by bieber on 14-11-5.
 */
public class SafeFile extends ReentrantReadWriteLock {

    private String filePath;

    private volatile long lastUpdateTime=-1;

    public SafeFile(String filePath){
        this.filePath = filePath;
    }

    private File getFile(){
        File file = new File(filePath);
        if(file.exists()&&lastUpdateTime<0){
            lastUpdateTime = file.lastModified();
        }else{
            File dir = new File(file.getParent());
            if(!dir.exists()){
                dir.mkdirs();
            }
        }
        return file;
    }

    private InputStream getInputStream() throws FileNotFoundException {
        return new FileInputStream(getFile());
    }

    private OutputStream getOutputStream() throws FileNotFoundException {
        return new FileOutputStream(getFile());
    }

    public long getLastUpdateTime(){
        return lastUpdateTime;
    }

    public String read() throws IOException {
        Lock lock = readLock();

        try {
            lock.lockInterruptibly();
        } catch (InterruptedException e) {
            Utils.COMMONS_LOGGER.debug("lock exception ", e);
        }
        InputStream in  = null;
        try{
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int offset = -1;
            in = getInputStream();
            while((offset=in.read(buffer,0,1024))>0){
                byteArrayOutputStream.write(buffer,0,offset);
            }
            return new String(byteArrayOutputStream.toByteArray(), JBeer.getApplicationEncode());
        }catch(FileNotFoundException e){
            Utils.COMMONS_LOGGER.debug("file not found ",e);
            return "{}";
        }finally {

            lock.unlock();
            if(in !=null){
                in.close();
            }
        }

    }


    public void write(String content) throws IOException {
        Lock lock = writeLock();

        try {
            lock.lockInterruptibly();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        OutputStream out = null;
        try{
            out = getOutputStream();
            out.write(content.getBytes(JBeer.getApplicationEncode()));
        }finally {
            lock.unlock();
            if(out!=null){
                out.close();
            }
            lastUpdateTime = System.currentTimeMillis();
        }

    }
}
